<template>
  <div class="c-ph24 audioPlay" @click="clickAudioCom">
    <!-- 顶部封面和播放器背景 -->
    <div class="c-w100 c-hh280 c-flex-row c-flex-center c-p">
      <div @click="clickCover" class="c-maxw300 c-hh200 c-flex-row c-flex-center c-p c-pz2">
        <img class="c-maxw c-hh200 img-pe-none c-br20" :src="$addXossFilter(cover)" alt="">
        <div v-if="!(isIosApp || isAndoridApp) && hasPermission && showPlayBack && ckFrom != 78" @click.stop="listenBack" class="audio-back-play-tag c-pa c-p-r0 c-p-b0">
          <i class="iconfont c-fc-white c-fs32">&#xe753;</i>
          <span class="c-ml4">后台播放</span>
        </div>
      </div>
      <div class="audio-playing-ani"><span v-for="i in 36" :key="i"></span></div>
    </div>

    <!-- 播放器前进后退15s和进度条 -->
    <div class="c-flex-row c-aligni-center">
      <i class="iconfont icon-kuaitui15miao1 c-fc-xblack c-fs44  c-pr10" @click="beforeFifteen"></i>
      <div class="c-flex-grow1 c-w0 c-ph20 c-flex-row">
        <div style="width: 34px;height: 4px;padding: 7px 0 7px 0;">
          <div class="process-style2" style="height: 4px"></div>
        </div>
        <div class="c-flex-grow1 c-w0">
          <vue-slider ref="slider" :contained="true" :height="4" :processStyle="processStyle2" :railStyle="railStyle2" v-model="audioPlayTime" tooltip="none" :lazy="true" min="0" :max="duration"
            @drag-start="dragStart" @dragging="dragging" @drag-end="dragEnd" @change="inputChange">
            <template slot="dot">
              <div class="dot-inner">
                <span>{{ slideValFomat }}/{{ durationTimeFomat }}</span>
              </div>
            </template>
          </vue-slider>
        </div>
        <div style="width: 34px;height: 4px;padding: 7px 0 7px 0;">
          <div class="rail-style" style="height: 4px"></div>
        </div>
      </div>
      <i class="iconfont icon-kuaijin15miao1 c-fc-xblack c-fs44 c-pl10" @click="nextFifteen"></i>
    </div>
    <!-- 播放器控制栏 -->
    <div class=" c-flex-row c-flex-center c-p c-mt32">
      <div class="c-pa  c-p-l0 c-p-t20 c-ww80 c-hh80 c-flex-column c-flex-center" :class="isFromColumn || !hasPermission ? 'c-opacity40':''" @click="changePlayType">
        <i class="iconfont c-fs32 c-fc-xblack" :class="playTypeIconMap[playType]"></i>
        <span class="c-fs16 c-fc-gray c-mt4">{{playTypeNameMap[playType]}}</span>
      </div>
      <span v-if="ckFrom != 78" @click="clickBefor" class="iconfont c-fs44 c-fc-xblack" :class="!canCut ? 'c-opacity40':''" >&#xe7c4;</span>
      <div class="c-mh72 c-flex-row c-flex-center c-p" @click="checkSubscribeBeforePlay" >
        <div class="c-p c-ww80 c-hh80">
          <div class="c-bg-sblack c-ww80 c-hh80 c-flex-row c-flex-center c-brp50">
            <i class="iconfont c-fc-white c-fs42" :class="playStatusIconMap[playStatus]"></i>
          </div>
          <wx-open-audio v-if="isUseWxOpenAudio" id="audioPlayer" :title="audioTitle" :type="isHls" :src="audioSrc" :playbackRate="playbackRate" :class="(isSaleOnly == 1 && payType == 1 && cfg && cfg.enableSubscribeWechat == 1 && isSubscribe == false) || formflag || canNotPlay || (bindPhoneSetting && bindPhoneSetting.getBind)? 'c-pz-1' : ''" class="c-ww90 c-hh90 c-pa c-p-t0 c-opacity0"></wx-open-audio>
        </div>
        <span v-show="hasAuditionPermission && !isClicked" class="c-pa c-pv2 c-ph10 c-fc-white c-br20 c-fs18 audio-auditon">试学</span>
      </div>
      <span v-if="ckFrom != 78" @click="clickAfter" class="iconfont c-fs44 c-fc-xblack":class="!canCut ? 'c-opacity40':''" >&#xe7c3;</span>
      <div @click="clickSpeed" v-if="speedPlay" class="c-pa c-p-r0 c-p-t20 c-ww80 c-hh80 c-fc-xblack c-flex-column c-flex-center">
        <i v-if="playbackRate == 1" class="iconfont icon-beishu1 c-fs32"></i>
        <span v-else class="c-fs28" >{{playbackRate}}X</span>
        <span class="c-fs16 c-fc-gray c-mt4">倍速</span>
      </div>
    </div>
    <!-- H5原生音频播放器 -->
    <audio id="audioPlayer" class="c-pf c-p-l-100" :title="audioTitle" v-if="!isUseWxOpenAudio">
      <source id="audioSource" src="" type="audio/mpeg" />
    </audio>
    <!-- 倍数选择弹窗 -->
    <cj-actionsheet v-model="showSpeedModal"  :item-list="speedList" get-container="body" @choose="clickMenu" ></cj-actionsheet>
    <!-- 小程序二维码弹窗 -->
    <cj-popup v-model="isShowMiniQr" round closeable get-container="body">
      <div class="c-ww520 c-ph48 c-pt60 c-pb80 c-br20 c-textAlign-c c-p">
        <div class="c-fs28 c-fc-xblack c-lh40 c-mb40 c-fw-b">
          长按识别小程序码 边聊微信边听
        </div>
        <img v-if="miniQr" class="c-w250 c-hh250 c-m-0auto" :src="$addXossFilter(miniQr)" />
        <div v-else class="c-w250 c-hh250 c-bg-white"></div>
      </div>
    </cj-popup>
  </div>
</template>
<script>
import VueSlider from "vue-slider-component";
import "vue-slider-component/theme/antd.css";
import { utilJs } from "@/utils/common.js";
import { PLAY_TYPE_ICON_MAP, PLAY_TYPE_NAME_MAP } from "@/utils/constant.js";
import { audioTool } from "@/utils/audioTool.js";
const Hls = require("hls.js");
const IS_IOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
// import SliderCom from "@/components/templates/common/audio/SliderCom.vue";
let playTimeControl = null;
// let isFirstPlay = true; //是否第一次赋值src，是的话第一次不播放
let isDeactivated = false; //是否销毁对象，解决销毁了会继续出发audioTimeUpdate 导致audioTime无法为0
let isCanPlay = false; //是否能开始播放音频
let pageStatus = "visible";
// let dragStartTime = 0;
// let isPlaySuccess = 0;
let hiddenPlay = 0;
export default {
  name: "",
  components: {
    VueSlider,
  },
  props: {
    cover: {
      type: String,
      default: ''
    },
    watchTime: { //秒
      type: Number,
      default: 0
    },
    audioTitle: {
      type: String,
      default: "音频详情"
    },
    audioAndSrc: {
      type: String,
      default: ""
    },
    audioIOSSrc: {
      type: String,
      default: ""
    },
    hasPermission: {
      type: Boolean,
      default: false
    },
    curPlayTime: {
      type: Number,
      default: 0
    },
    totalPlayedTime: {
      type: Number,
      default: 0
    },
    showPlayBack: {
      type: Boolean,
      default: false
    },
    hasAuditionPermission: {
      type: Boolean,
      default: false
    },
    miniQr: {
      type: String,
      default: ""
    },
    isCourseChange: {
      //从音频课程跳转到音频课程的时候，会自动开始播放，所以加上控制
      type: Boolean,
      default: false
    },
    isNeedFirstPlay: {
      //为true时，第一次赋值src也能播放
      type: Boolean,
      default: false
    },
    isAllowProgressBar: {
      type: Boolean,
      default: true
    },
    appAudioInfo: {//app播放需要的信息
      type: Object,
      default: () => {
        return null;
      }
    },
    appNeedPlayThis: {//app是否需要立即播放当前音频
      type: Number,
      default: 0
    },
    playType: {//音频播放顺序
      type: Number,
      default: 1
    },
    currentIndex: {//当前播放到第几节
      type: Number,
      default: 0
    },
    payType: { //付费类型
      type: Number,
      default: 2
    },
    isSaleOnly: {
      type: Number, //是否支持单卖
      default: 2
    },
    formflag:{
      type: Boolean,
      default: false
    },
    canNotPlay: {
      type: Boolean,
      default: false
    },
    isFromColumn: {
      type: Boolean,
      default: false
    },
    isSubscribe: {
      type: Boolean,
      default: true
    },
    bindPhoneSetting: {
      type: Object,
      default: () => {
        return null;
      }
    },
    speedPlay: {
      type: Boolean, //是否显示倍速播放
      default: true
    },
    canCut: {
      type: Boolean, //是否可以切换上一首、下一首
      default: true
    },
  },
  computed: {
    slideValFomat() {
      if (!this.isMounted) {
        return;
      }
      let $this = this;
      // setTimeout(function () {
      let minutes = Math.floor($this.$refs.slider.getValue() / 60);
      let seconds = Math.floor($this.$refs.slider.getValue() % 60);
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      return `${minutes}:${seconds}`;
      // }, 1000)
    },
    curPlayTimeFomat() {
      let minutes = Math.floor(this.audioPlayTime / 60);
      let seconds = Math.floor(this.audioPlayTime % 60);
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      return `${minutes}:${seconds}`;
    },
    durationTimeFomat() {
      let minutes = Math.floor(this.duration / 60);
      let seconds = Math.floor(this.duration % 60);
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      return `${minutes}:${seconds}`;
    }
  },
  watch: {
    hasPermission() {
      this.isUseWxOpenAudio = this.getIsUseWxOpenAudio();
    },
    appAudioInfo: {
      handler(val, oldVal) {
        console.log('----切换章节---', this.isAndoridApp, this.isIosApp)
        if (val) {
          this.appAudioInit();
        }
      },
      immediate: true,
    },
    isCourseChange: {
      handler(val, oldVal) {
        if (val) {
          // this.playStatus = 0;
          if (this.playStatus == 1) {
            this.audioPause();
          }
          this.isFirstPlay = true;
        }
      }
    },
    playType: {
      handler(val, oldVal) {
        if (this.isAndoridApp || this.isIosApp) {
          this.appAudioPlayTypeChange();
        }
      }
    },
    audioAndSrc: {
      handler(val, oldVal) {
        //原生app流程
        if (this.isAndoridApp) {
          this.appAudioSrcChanged('andSrc', val);
          return;
        }
        //如果是iosapp ，并且版本是在13以下，那么就播放mp3的
        let isIos = navigator.userAgent
          .toLowerCase()
          .match(/cpu iphone os (.*?) like mac os/);
        let isIos13Min =
          isIos && isIos.length > 0
            ? isIos[1]
              .replace(/_/g, ".")
              .toString()
              .split(".")[0] < 13
              ? true
              : false
            : false;
        let iosAppMp3 = utilJs.isIOSAppALL() && isIos13Min;
        if (!val || this.isIosApp || (IS_IOS && !iosAppMp3)) {
          return;
        }
        console.log(
          "newANDSrc d: %s, oldSrc: %s",
          val,
          oldVal,
          !this.isFirstPlay,
          this.isNeedFirstPlay
        );
        isCanPlay = false;
        this.playStatus = 2;
        this.isHls = " ";
        if (!this.aduioObj) {
          this.aduioObj = document.getElementById("audioPlayer");
        }
        this.audioPlayTime = 0;
        if (!this.isUseWxOpenAudio) {
          document.getElementById("audioPlayer").src = val;
          document.getElementById("audioSource").src = val;
          let audio = document.getElementById("audioPlayer");
          utilJs.audioPlayFun(audio, "load");
        } else {
          this.audioSrc = val;
          // this.aduioObj.load();
          this.initAudio();
        }
        // isPlaySuccess = 0;
        if (!this.isFirstPlay || this.isNeedFirstPlay) {
          setTimeout(() => {
            this.audioPlay();
          }, 400);
        }
      }
    },
    audioIOSSrc: {
      handler(val, oldVal) {
        //原生app流程
        if (this.isIosApp) {
          this.appAudioSrcChanged('iosSrc', val);
          return;
        }
        //如果是iosapp ，并且版本是在13以下，那么就播放mp3的
        let isIos = navigator.userAgent
          .toLowerCase()
          .match(/cpu iphone os (.*?) like mac os/);
        let isIos13Min =
          isIos && isIos.length > 0
            ? isIos[1]
              .replace(/_/g, ".")
              .toString()
              .split(".")[0] < 13
              ? true
              : false
            : false;
        let iosAppMp3 = utilJs.isIOSAppALL() && isIos13Min;
        if (!val || !IS_IOS || iosAppMp3) {
          return;
        }
        console.log(
          "newIOSSrc d: %s, oldSrc: %s",
          val,
          oldVal,
          !this.isFirstPlay,
          this.isNeedFirstPlay
        );
        isCanPlay = false;
        this.playStatus = 2;
        this.isHls = "hls";
        // isPlaySuccess = 0;
        if (!this.aduioObj) {
          this.aduioObj = document.getElementById("audioPlayer");
        }
        this.audioPlayTime = 0;
        if (!this.isUseWxOpenAudio) {
          document.getElementById("audioPlayer").src = val;
          document.getElementById("audioSource").src = val;
          let audio = document.getElementById("audioPlayer");
          utilJs.audioPlayFun(audio, "load");
        } else {
          this.audioSrc = val;
          this.initAudio();
        }
        if (!this.isFirstPlay || this.isNeedFirstPlay) {
          setTimeout(() => {
            this.audioPlay();
          }, 400);
        }
      }
    },
    curPlayTime: {
      handler(val, oldVal) {
        if (!val) {
          return;
        }
        console.log(
          "curPlayTime new d: %s, old: %s",
          val,
          oldVal,
          this.audioPlayTime,
          this.duration
        );
        //app切换下一首时候总时长小于当前进度时间，需要特殊处理下
        if (this.duration > 5 && val > this.duration) {
          this.duration = (val * 1 + 10);
        }
        setTimeout(() => {
          if (!this.isUseWxOpenAudio) {
            this.setAudioCurrentTime(val);
          } else {
            this.audioPlayTime = val;
            this.hisPlayTime = Math.floor(val);
          }
        }, 200);
      }
    }
  },
  data() {
    return {
      speedList: [
        {
          name: "0.7x",
          value: 0.7
        },
        {
          name: "1.0x",
          value: 1
        },
        {
          name: "1.2x",
          value: 1.2
       },
       {
          name: "1.5x",
          value: 1.5
       },
       {
          name: "2.0x",
          value: 2.0
       },
      ],
      processStyle: {
        "background-color": "#569EF8"
      },
      railStyle: {
        "background-color": "#ededed"
      },
      dotOptions: {
        style: {
          border: "1px solid rgba(255,255,255,1)",
          "box-shadow": "0px 2px 5px 0px rgba(0, 0, 0, 0.2)"
        },
        focusStyle: {
          border: "2px solid #389ce7"
        }
      },
      dotStyle: {
        'width': '4px',
        'height': '6px',
        'background': '#333',
        'border-radius': '1px',
        'margin-top': '5px',
        'border': 'none'
      },
      processStyle2: {
        "background-color": "#333",
        "border-radius": "0"
      },
      railStyle2: {
        "background-color": "rgba(242, 242, 242, 0.5)"
      },
      playStatus: 0, // 播放状态
      duration: 0, //总时长
      playbackRate: 1, //播放速度
      audioPlayTime: 0,
      showSpeedModal: false,
      dragFlag: false,
      isShowMiniQr: false,
      isClicked: false,
      ckFrom: this.$route.query.ckFrom,
      isMounted: false,
      isUseWxOpenAudio: false, //是否使用微信开放音频标签
      isHls: "", //微信开放标签如果是m3u8的话要传type='hls'
      audioSrc: "",
      aduioObj: null, //音频全局话，防止开放标签重新
      hisPlayTime: 0, //上次学习到的时间，主要是开放标签用
      isIosApp: false,
      isAndoridApp: false,
      isRateMenuClickChange: false, //用于开放标签第二次进入页面，防止播放倍数变为默认
      cfg: JSON.parse(localStorage.getItem("cfg")),
      isFirstPlay: true,
      playTypeIconMap:PLAY_TYPE_ICON_MAP,
      playTypeNameMap:PLAY_TYPE_NAME_MAP,
      playStatusIconMap:{
        0:'icon-bofang9',
        1:'icon-zanting8',
        2:'icon-jiazaizhong',
      },
    };
  },

  methods: {
    /**
     * 获取是否使用微信开放音频标签播放
     */
    getIsUseWxOpenAudio() {
      const useAudioIdArr = ['7vn84jr']; //调试用，这些id只用原生标签，不用微信开放标签

      let isSystemSupport = audioTool.checkMobileVersion();
      //系统不支持，没办法使用开放标签
      if (!isSystemSupport) {
        return false;
      }
      //来自专栏直接默认不使用开放标签
      // if (this.isFromColumn) {
      //   return false;
      // }
      //没权限，也不使用开放标签
      if (!this.hasPermission) {
        return false;
      }
      //需要绑定手机号 && 手机号还没绑定，也不使用开放标签
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind && !localStorage.getItem('uMobile')) {
        return false;
      }
      //调试的用户不使用微信开放标签
      if (useAudioIdArr.includes(localStorage.getItem('userId'))) {
        return false;
      }
      // 是否使用微信开放标签
      const isCloseWxAudio = localStorage.getItem("MP_IS_CLOSE_WX_AUDIO");
      if (isCloseWxAudio == 1) {
        return false;
      }
      return true;
    },
    clickCover() {
      this.$emit('clickCover')
    },
    changePlayType() {
      if (!this.hasPermission || this.isFromColumn) {
        return;
      }
      this.$emit('changePlayType')
    },
    //********原生app播放相关start*****
    appAudioSrcChanged(val, srcType) {
      if (!val) {
        return;
      }
      //安卓手机只处理安卓地址
      if (srcType == 'andSrc' && !this.isAndoridApp) {
        return;
      }
      //苹果手机只处理苹果地址
      if (srcType == 'iosSrc' && !this.isIosApp) {
        return;
      }
      isCanPlay = false;
      this.playStatus = 2;
      this.audioPlayTime = 0;
      if (!this.isFirstPlay || this.isNeedFirstPlay) {
        setTimeout(() => {
          this.audioPlay();
        }, 400);
      } else {
        this.appAudioInit();
      }
    },
    //app播放顺序改变
    appAudioPlayTypeChange() {
      let appData = {
        playType: this.playType,
      }
      console.log('---appAudioPlayTypeChange---')
      utilJs.sendDataToApp('appAudioPlayTypeChange', appData)
    },
    //app开始播放
    appAudioInit() {
      let appData = {
        iOSAudioSrc: this.audioIOSSrc,
        androidAudioSrc: this.audioAndSrc,
        curPlayTime: this.curPlayTime,
        audioInfo: this.appAudioInfo, //播放列表
      }
      console.log('---appAudioInit---')
      utilJs.sendDataToApp('appAudioInit', appData)
    },
    //app开始播放
    appAudioPlay() {
      if (hiddenPlay == 1) {
        hiddenPlay = 0;
      }
      let appData = {
        iOSAudioSrc: this.audioIOSSrc,
        androidAudioSrc: this.audioAndSrc,
        curPlayTime: this.hisPlayTime != 0 ? this.curPlayTime : this.audioPlayTime,
        needPlayThis: this.appNeedPlayThis, //是否是自动播放下一首的
      }
      utilJs.sendDataToApp('appAudioPlay', appData)
    },
    //app暂停播放
    appAduioPause() {
      this.playStatus = 0;
      let appData = {
        iOSAudioSrc: this.audioIOSSrc,
        androidAudioSrc: this.audioAndSrc,
      }
      utilJs.sendDataToApp('appAudioPause', appData)
      clearInterval(playTimeControl);
      this.$emit("audioPause");
    },
    //app设置进度时间
    setAppAudioCurrentTime(time) {
      let appData = {
        iOSAudioSrc: this.audioIOSSrc,
        androidAudioSrc: this.audioAndSrc,
        curPlayTime: parseInt(time),
      }
      utilJs.sendDataToApp('setAppAudioCurrentTime', appData)
    },
    //app设置倍数
    setAppAudioPlaybackRate() {
      let appData = {
        iOSAudioSrc: this.audioIOSSrc,
        androidAudioSrc: this.audioAndSrc,
        playbackRate: this.playbackRate,
      }
      console.log('----setAppAudioPlaybackRate---')
      utilJs.sendDataToApp('setAppAudioPlaybackRate', appData)
    },
    //拖动结束触发app操作
    appDragEnd(dragTime) {
      //拖动的时间大于之前已播放的时间 && 拖动的时间大于学习记录里的进度 && 禁止拖动  则禁止拖动
      if (dragTime > this.audioPlayTime && this.audioPlayTime > this.totalPlayedTime && !this.isAllowProgressBar && this.hasPermission) {
        this.$showCjToast({
          text: "该课程被限制快进，请学完后再试",
          type: "text",
        });
        this.dragFlag = false;
        if (this.playStatus == 0) {
          let that = this;
          setTimeout(function () {
            that.setAudioCurrentTime(dragTime);
          }, 500);
        }
        return;
      }
      this.setAudioCurrentTime(dragTime);
      this.dragFlag = false;
    },
    initGetAppData() {
      window['cjAppAudioOnPlay'] = this.appOnPlayEvent;
      window['cjAppAudioOnPause'] = this.appOnPauseEvent;
      window['cjAppAudioCanPlay'] = this.appCanPlayEvent;
      window['cjAppAudioEnd'] = this.appEndEvent;
      window['cjAppAudioError'] = this.appErrorEvent;
      window['cjAppAudioTimeUpdate'] = this.appTimeUpdateEvent;
    },
    appOnPlayEvent(durationNum) {
      console.log('---appOnPlayEvent--')
      if (durationNum) {
        this.duration = Math.floor(durationNum); //总进度不能是小数
      }
      this.playStatus = 1;
      this.isFirstPlay = false;
      this.$emit("startPlay");
      if (this.$store.state.oem_store.isFirstPlayAudio) {
        this.$store.commit("updateIsFirstPlayAudio", false);
      }
    },
    appOnPauseEvent(e) {
      console.log('---appOnPauseEvent--')
      console.log(e)
      this.playStatus = 0;
      clearInterval(playTimeControl);
      this.$emit("audioPause");
    },
    appCanPlayEvent(e) {
      console.log('---appCanPlayEvent--')
      console.log(e)
      if (this.isFirstPlay) {
        this.playStatus = 0;
      }
      this.duration = Math.floor(e); //总进度不能是小数
      this.isFirstPlay = false;
      isCanPlay = true;
      this.$emit("audioCanplay", this.duration);
    },
    appTimeUpdateEvent(time, appCurIndex) {
      console.log('---appTimeUpdateEvent-time-%s,index--%s', time, appCurIndex)
      if (isDeactivated || !isCanPlay || this.dragFlag || pageStatus == "hidden") {
        return;
      }
      //ios在暂停的时候还会回调这个，导致暂停了还是播放状态，需要去掉
      if (this.isAndoridApp) {
        this.playStatus = 1;
      }
      this.hisPlayTime = 0;
      //app切换下一首导致播放下标对不上，需要重置
      if (this.currentIndex != appCurIndex) {
        this.$emit('appChangePlayIndex', appCurIndex);
        return;
      }
      //当前时长>总时长就不更新
      if (time > this.duration) {
        return;
      }
      playTimeControl = setTimeout(() => {
        this.audioPlayTime = time;
        this.$emit("onPlayTimeChange", this.audioPlayTime, this.duration);
        if (
          !this.hasPermission &&
          this.watchTime &&
          this.audioPlayTime > this.watchTime &&
          this.playStatus == 1
        ) {
          this.audioPause();
          this.$emit("watchEnd");
          this.audioPlayTime = 0;
        }
      }, 200);
    },
    appEndEvent(e) {
      console.log('---appEndEvent--')
      console.log(e)
      this.audioPlayEnd();
    },
    appErrorEvent(e) {
      console.log('---appErrorEvent--')
      console.log(e)
    },
    //********原生app播放相关end*****
    initAudio() {
      if (this.isIosApp || this.isAndoridApp) {
        this.initGetAppData();
        return;
      }
      document.removeEventListener("visibilitychange", this.visibilitychange);
      document.addEventListener("visibilitychange", this.visibilitychange);
      document
        .getElementById("audioPlayer")
        .removeEventListener("play", this.onPlay);
      document
        .getElementById("audioPlayer")
        .removeEventListener("pause", this.onPause);
      document
        .getElementById("audioPlayer")
        .removeEventListener("error", this.audioError);
      document
        .getElementById("audioPlayer")
        .removeEventListener("timeupdate", this.audioTimeUpdate);
      document
        .getElementById("audioPlayer")
        .removeEventListener("canplay", this.audioCanPlay);
      document
        .getElementById("audioPlayer")
        .removeEventListener("canplaythrough", this.canplaythrough);
      document
        .getElementById("audioPlayer")
        .removeEventListener("ended", this.audioPlayEnd);
      document
        .getElementById("audioPlayer")
        .addEventListener("play", this.onPlay);
      document
        .getElementById("audioPlayer")
        .addEventListener("pause", this.onPause);
      document
        .getElementById("audioPlayer")
        .addEventListener("error", this.audioError);
      document
        .getElementById("audioPlayer")
        .addEventListener("timeupdate", this.audioTimeUpdate);
      document
        .getElementById("audioPlayer")
        .addEventListener("canplay", this.audioCanPlay);
      document
        .getElementById("audioPlayer")
        .addEventListener("canplaythrough", this.canplaythrough);
      document
        .getElementById("audioPlayer")
        .addEventListener("ended", this.audioPlayEnd);
    },
    setAudioCurrentTime(time) {
      if (this.isIosApp || this.isAndoridApp) {
        this.setAppAudioCurrentTime(time);
        return;
      }
      if (!document.getElementById("audioPlayer")) {
        return;
      }
      document.getElementById("audioPlayer").currentTime = Math.floor(time);
    },
    setAudioPlaybackRate() {
      if (this.isIosApp || this.isAndoridApp) {
        this.setAppAudioPlaybackRate();
        return;
      }
      if (!document.getElementById("audioPlayer")) {
        return;
      }
      document.getElementById("audioPlayer").playbackRate = this.playbackRate;
    },
    beforeFifteen() {
      // if (!this.hasPermission) {
      //   return;
      // }
      let beforeFifteenTime =
        this.audioPlayTime < 15 ? 0 : this.audioPlayTime - 15;
      this.$refs.slider.setValue(Math.floor(beforeFifteenTime));
    },
    nextFifteen() {
      // if (!this.hasPermission) {
      //   return;
      // }
      if (!this.isAllowProgressBar) {
        this.$showCjToast({
          text: "该课程被限制快进，请学完后再试",
          type: "text",
        });
        return;
      }
      let nextFifteenTime =
        this.duration - this.audioPlayTime < 15
          ? this.duration
          : this.audioPlayTime * 1 + 15;
      this.$refs.slider.setValue(Math.floor(nextFifteenTime));
    },
    visibilitychange() {
      if (document.visibilityState === "hidden") {
        console.log("隐藏页面了*******");
        //试听切到后台暂停播放
        if (!this.hasPermission && this.watchTime * 1 > 0) {
          this.audioPause();
        }
        if (IS_IOS) {
          pageStatus = "hidden";
          hiddenPlay = 1;
        }
      } else if (document.visibilityState === "visible") {
        if (IS_IOS) {
          console.log("页面显示了*********");
          pageStatus = "visible";
          if (!this.aduioObj) {
            this.aduioObj = document.getElementById("audioPlayer");
          }
          //切到前台，获取当前的播放时间，防止播放失败的时候可以回到现在的时间
          if (this.aduioObj && this.aduioObj.curPlayTime > 0) {
            this.audioPlayTime = Math.floor(this.aduioObj.currentTime);
          } else if (!this.isUseWxOpenAudio && isCanPlay == false) {
            this.playStatus = 0;
          }
        }
      }
    },
    clickMenu(item) {
      this.isRateMenuClickChange = true;
      this.showSpeedModal = false;
      this.playbackRate = item.value;
      this.setAudioPlaybackRate()
      this.initAudio();
    },
    clickAudioCom() {
      this.$emit("clickNoPermission");
    },
    clickBefor() {
      if (!this.canCut)
        return;
      this.$emit("clickBefor");
    },
    onPlay() {
      if (!this.hasPermission && this.watchTime * 1 > 0 && IS_IOS && pageStatus == "hidden") {
        this.audioPause();
        return
      }
      this.playStatus = 1;
      if (this.isUseWxOpenAudio) {
        this.isFirstPlay = false;
      }
      if (document.getElementById("audioPlayer").playbackRate != this.playbackRate) {
        if (this.isUseWxOpenAudio) {
          if (this.isRateMenuClickChange == true) {
            this.setAudioPlaybackRate();
          } else {
            this.playbackRate = this.aduioObj.playbackRate;
          }
        } else {
          this.setAudioPlaybackRate();
        }
      }
      this.$emit("startPlay", this.playStatus);
      this.$emit('clickPlayBtn')
      if (this.$store.state.oem_store.isFirstPlayAudio) {
        this.$store.commit("updateIsFirstPlayAudio", false);
      }
      console.log("播放了*************", this.audioPlayTime);
    },
    onPause() {
      console.log("暂停了*************");
      this.playStatus = 0;
      clearInterval(playTimeControl);
      this.$emit("audioPause", this.playStatus);
      if (!this.isUseWxOpenAudio) {
        if (!this.aduioObj) {
          this.aduioObj = document.getElementById("audioPlayer");
        }
        //获取当前的播放时间，防止播放失败的时候可以回到现在的时间
        if (IS_IOS && this.aduioObj && this.aduioObj.currentTime > 0) {
          this.audioPlayTime = Math.floor(this.aduioObj.currentTime);
        }
      }
    },
    getIsSubscribe() {
      let $this = this;
      return new Promise(function (resolve, reject) {
        utilJs.getMethod(`${global.apiurl}company/getSubscribe`,
          res => {
            $this.$emit('checkIsSubscribe', res)
            // $this.dataInfo.isSubscribe = res;
            resolve(res);
          },
          failRes => {
            reject(failRes)
          }
        )
      })
    },
    //检查是否已经关注
    checkSubscribeBeforePlay() {
      if (this.isSaleOnly == 1 && this.payType == 1 && this.cfg && this.cfg.enableSubscribeWechat == 1 && this.isSubscribe == false) {
        this.getIsSubscribe().then(res => {
          this.$nextTick(() => {
            this.clickPlay()
          })
        })
      } else {
        this.clickPlay()
      }
    },
    //点击播放/暂停 按钮
    clickPlay() {
      console.log("clickPlayclickPlayclickPlay");
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile({
            isFromInvite: 0,
            isGoPay: false
        })) return;
      }
      if ((!this.audioAndSrc && !IS_IOS) || (!this.audioIOSSrc && IS_IOS)) {
        return;
      }
      if (this.canNotPlay) {
        return;
      }
      this.isClicked = true;
      // isPlaySuccess = 1;
      //有权限，免费或付费购买前表单，非强制
      if (this.hasPermission && this.formflag) {
        this.$emit('goForm');
        return
      }
      if (this.playStatus == 1) {
        this.audioPause();
      } else {
        if (this.isSaleOnly == 1 && this.payType == 1 && this.cfg && this.cfg.enableSubscribeWechat == 1 && this.isSubscribe == false && utilJs.isWeiXin()) {
          this.$emit('showFollowQr');
          return;
        }
        this.playStatus = 2;
        this.audioPlay();
      }
    },
    clickAfter() {
      if (!this.canCut)
        return;
      this.$emit("clickAfter");
    },
    clickSpeed() {
      this.showSpeedModal = true;
    },
    //使用hls播放
    playAudioHls(src, hlsStr) {
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      let audioSource = {};
      if (!this.isUseWxOpenAudio) {
        audioSource = document.getElementById("audioSource");
      }
      this.initAudio();
      this.isHls = hlsStr;
      // HLS support ios直播播放m3u8 安卓使用hls播放
      if (
        !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ||
        this.isUseWxOpenAudio
      ) {
        console.log("m3u8换成安卓路径", navigator.userAgent);
        if (!this.isUseWxOpenAudio) {
          audioSource.src = src;
          document.getElementById("audioPlayer").src = src;
          let audio = document.getElementById("audioPlayer");
          utilJs.audioPlayFun(audio, "load");
        } else {
          this.audioSrc = src;
          this.initAudio();
        }
        if (!this.isFirstPlay || this.isNeedFirstPlay) {
          this.audioPlay();
        }
      } else {
        console.log("不支持支持播放m3u8");
        try {
          if (Hls.isSupported()) {
            if (!this.hls) {
              this.hls = new Hls();
            }
            this.hls.loadSource(src);
            this.hls.attachMedia(this.aduioObj);
            if (!this.isFirstPlay || this.isNeedFirstPlay) {
              this.audioPlay();
            }
          } else {
            console.log("HLS is not supported on your browser");
            if (!this.isUseWxOpenAudio) {
              audioSource.src = src;
              document.getElementById("audioPlayer").src = src;
              let audio = document.getElementById("audioPlayer");
              utilJs.audioPlayFun(audio, "load");
            } else {
              this.audioSrc = src;
              this.initAudio();
            }
            if (!this.isFirstPlay || this.isNeedFirstPlay) {
              this.audioPlay();
            }
          }
        } catch (e) {
          console.log("hls.js is required to support m3u8");
          if (!this.isUseWxOpenAudio) {
            audioSource.src = src;
            document.getElementById("audioPlayer").src = src;
            let audio = document.getElementById("audioPlayer");
            utilJs.audioPlayFun(audio, "load");
          } else {
            this.audioSrc = src;
            this.initAudio();
          }
          if (!this.isFirstPlay || this.isNeedFirstPlay) {
            this.audioPlay();
          }
        }
      }
    },
    //播放失败，如果IOS则替换成播放mp4,如果是安卓，则替换成m3u8
    audioError(e) {
      console.log("eeeeeeeeeee", e);
      if (e.detail && e.detail.errMsg && (e.detail.errMsg == "pause:fail" || e.detail.errMsg == "play:fail") && !sessionStorage.getItem("jsConfigError")) {
        // 开放标签如果报错了，就用正常的音频标签播放
        sessionStorage.setItem("jsConfigError", 1);
        if (window.location.href.split("#")[1].indexOf("?") > -1) {
          window.location.href = `${window.location.href}&time=${new Date().getTime()}`;
        } else {
          window.location.href = `${window.location.href}?time=${new Date().getTime()}`;
        }
        window.location.reload();
        return;
      }
      // if (isPlaySuccess == 1) {
      //   return;
      // }
      this.playStatus = 0;
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      if (
        IS_IOS &&
        ((this.isUseWxOpenAudio && this.aduioObj.src == this.audioIOSSrc) ||
          (!this.isUseWxOpenAudio &&
            document.getElementById("audioPlayer").src == this.audioIOSSrc))
      ) {
        //获取当前的播放时间，防止播放失败的时候可以回到现在的时间
        if (IS_IOS && this.aduioObj && this.aduioObj.currentTime > 0) {
          this.audioPlayTime = Math.floor(this.aduioObj.currentTime);
        }
        this.playAudioHls(this.audioAndSrc, "");
      } else if (
        !IS_IOS &&
        ((this.isUseWxOpenAudio && this.aduioObj.src == this.audioAndSrc) ||
          (!this.isUseWxOpenAudio &&
            document.getElementById("audioPlayer").src == this.audioAndSrc))
      ) {
        this.playAudioHls(this.audioIOSSrc, "hls");
      } else {
        this.playStatus = 0;
        if (this.isUseWxOpenAudio) {
          this.$showCjToast({
            text:
              "资源加载失败，已为您切换播放方式，请重新点击播放按钮进行播放！",
            type: "text",
          });
          if (IS_IOS && this.aduioObj && this.aduioObj.currentTime > 0) {
            this.audioPlayTime = Math.floor(this.aduioObj.currentTime);
          }
          this.isUseWxOpenAudio = false;
          this.$nextTick(() => {
            this.aduioObj = document.getElementById("audioPlayer");
            this.initAudio();
            this.$nextTick(() => {
              this.audioSrc = IS_IOS ? this.audioIOSSrc : this.audioAndSrc;
              document.getElementById("audioPlayer").src = this.audioSrc;
              document.getElementById("audioSource").src = this.audioSrc;
              utilJs.audioPlayFun(
                document.getElementById("audioPlayer"),
                "load"
              );
              if (!this.isFirstPlay || this.isNeedFirstPlay) {
                this.audioPlay();
              }
            });
          });
        } else {
          this.$showCjToast({
            text: "资源加载失败，请刷新页面！",
            type: "text",
          });
        }
      }
      let errorData = {
        errorType: "AUDIO_PLAY_ERROR",
        errorContent: JSON.stringify(e),
        errorAdSrc: this.audioAndSrc,
        errorIosSrc: this.audioIOSSrc,
        errorCurTime: this.aduioObj.currentTime,
        errorCurSrc: this.aduioObj.src
      };
      utilJs.reprotError(errorData);
      console.log("audioError****");
      console.log(e);
      console.log(this.aduioObj.src);
      console.log(this.aduioObj.currentTime);
      console.log(this.audioIOSSrc);
      console.log("audioErrorEND****");
    },
    //重新开始播放
    rePlay() {
      console.log("rePlay");
      if (this.isIosApp || this.isAndoridApp) {
        this.appAudioPlay();
        return;
      }
      if (!this.isUseWxOpenAudio) {
        let audio = document.getElementById("audioPlayer");
        utilJs.audioPlayFun(audio, "load");
      } else {
        this.initAudio();
      }
      this.audioPlay();
    },
    audioPlayEnd() {
      this.audioPlayTime = 0;
      this.playStatus = 0;
      clearInterval(playTimeControl);
      this.$emit("audioPlayEnd", pageStatus);
    },
    //开始播放音频
    audioCanPlay(e) {
      if (this.isFirstPlay && !this.isNeedFirstPlay) {
        this.playStatus = 0;
      }
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      this.duration = this.isUseWxOpenAudio
        ? Math.floor(this.aduioObj.duration)
        : Math.floor(e.target.duration); //总进度不能是小数
      if (!this.isUseWxOpenAudio) {
        this.isFirstPlay = false;
      }
      isCanPlay = true;
      if (
        IS_IOS &&
        !this.isUseWxOpenAudio &&
        this.audioPlayTime * 1 > 0 &&
        document.getElementById("audioPlayer")
      ) {
        // this.setAudioCurrentTime(this.audioPlayTime)
      }
      this.$emit("audioCanplay", this.duration);
    },
    canplaythrough(e) {
      console.log("123123");
    },
    loadedmetadata(e) {
      console.log("loadedmetadata------");
    },
    audioTimeUpdate(e) {
      // //如果正在拖动 || 关闭页面 || 还不能播放，则不更新时间
      if (
        isDeactivated ||
        !isCanPlay ||
        this.dragFlag ||
        pageStatus == "hidden"
      ) {
        return;
      }
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      if (
        this.hisPlayTime != 0 &&
        this.isUseWxOpenAudio &&
        Math.floor(this.aduioObj.currentTime) >= 0 &&
        Math.floor(this.aduioObj.currentTime) <= this.hisPlayTime
      ) {
        this.audioPlayTime = Math.floor(this.hisPlayTime);
        this.setAudioCurrentTime(this.audioPlayTime);
        this.hisPlayTime = 0;
      }
      playTimeControl = setTimeout(() => {
        if (this.aduioObj && Math.floor(this.aduioObj.currentTime) > 0) {
          this.audioPlayTime = Math.floor(this.aduioObj.currentTime);
        }
        this.$emit("onPlayTimeChange", this.audioPlayTime, this.duration);
        if (
          !this.hasPermission &&
          this.watchTime &&
          this.audioPlayTime > this.watchTime &&
          this.playStatus == 1
        ) {
          if (!this.isUseWxOpenAudio) {
            let audio = document.getElementById("audioPlayer");
            utilJs.audioPlayFun(audio, "load");
          } else {
            this.initAudio();
          }
          this.audioPause();
          this.$emit("watchEnd");
        }
      }, 200);
    },
    audioPlay(e) {
      if (this.isIosApp || this.isAndoridApp) {
        this.appAudioPlay();
        return;
      }
      console.log("audioPlay------", this.aduioObj);
      console.log("audioPlayTime------" + this.audioPlayTime);
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      if (IS_IOS && hiddenPlay == 1) {
        if (!this.isUseWxOpenAudio) {
          document.getElementById("audioPlayer").src = this.audioIOSSrc;
          document.getElementById("audioSource").src = this.audioIOSSrc;
        } else {
          this.audioSrc = this.audioIOSSrc;
          this.initAudio();
        }
        hiddenPlay = 0;
      }
      this.$nextTick(() => {
        if (this.isUseWxOpenAudio) {
          if (isCanPlay) {
            utilJs.audioPlayFun(this.aduioObj);
          } else {
            setTimeout(() => {
              this.audioPlay();
            }, 600);
          }
        } else {
          let audio = document.getElementById("audioPlayer");
          utilJs.audioPlayFun(audio);
        }
      });
    },
    audioPause(e) {
      if (this.isIosApp || this.isAndoridApp) {
        this.appAduioPause();
        return;
      }
      this.playStatus = 0;
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      this.aduioObj.pause();
      clearInterval(playTimeControl);
      this.$emit("audioPause");
      console.log("audioPause------");
    },
    dragStart() {
      if (!isCanPlay && this.isUseWxOpenAudio) {
        return;
      }
      this.dragFlag = true;
      // dragStartTime = this.audioPlayTime;
    },
    dragging() {
      if (!isCanPlay && this.isUseWxOpenAudio) {
        return;
      }
      this.dragFlag = true;
      clearInterval(playTimeControl);
      console.log("dragging------");
    },
    //拖动结束，更改播放器当前时间，重新开始循环获取当前时间
    dragEnd() {
      if (this.isIosApp || this.isAndoridApp) {
        this.appDragEnd(this.audioPlayTime);
        return;
      }
      if (!isCanPlay && this.isUseWxOpenAudio) {
        return;
      }
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      //拖动的时间大于之前已播放的时间 && 拖动的时间大于学习记录里的进度 && 禁止拖动  则禁止拖动
      if (
        this.audioPlayTime > this.aduioObj.currentTime &&
        this.audioPlayTime > this.totalPlayedTime &&
        !this.isAllowProgressBar
      ) {
        this.$showCjToast({
          text: "该课程被限制快进，请学完后再试",
          type: "text",
        });
        this.dragFlag = false;
        if (this.playStatus == 0) {
          let that = this;
          setTimeout(() => {
            that.audioPlayTime = Math.floor(
              this.aduioObj.currentTime ? this.aduioObj.currentTime : 0
            );
          }, 500);
        }
        return;
      }
      this.setAudioCurrentTime(this.audioPlayTime);
      this.dragFlag = false;
      if (!IS_IOS && !this.isUseWxOpenAudio) {
        isCanPlay = false;
      }
      console.log("dragEnd-----------");
    },
    inputChange(value) {
      if (this.isIosApp || this.isAndoridApp) {
        this.appDragEnd(this.audioPlayTime);
        return;
      }
      if (!isCanPlay && this.isUseWxOpenAudio) {
        return;
      }
      if (!this.aduioObj) {
        this.aduioObj = document.getElementById("audioPlayer");
      }
      if (
        value > this.aduioObj.currentTime &&
        value > this.totalPlayedTime &&
        !this.isAllowProgressBar &&
        this.hasPermission
      ) {
        this.$showCjToast({
          text: "该课程被限制快进，请学完后再试",
          type: "text",
        });
        if (this.playStatus == 0) {
          let that = this;
          setTimeout(() => {
            that.audioPlayTime = Math.floor(
              this.aduioObj.currentTime ? this.aduioObj.currentTime : 0
            );
          }, 500);
        }
        return;
      }
      console.log("inputChange-----------");
      if (this.dragFlag) {
        this.dragFlag = false;
        return;
      }
      console.log("inputChange-----dragFlag------");
      this.setAudioCurrentTime(this.audioPlayTime);
    },
    listenBack() {
      this.$emit("getMiniQr");
      this.isShowMiniQr = true;
    }
  },
  mounted() {
    this.isIosApp = utilJs.isIosAudioApp() && this.hasPermission && !this.isFromColumn; //试听暂时先走网页流程，带app同事改好后再走原生
    this.isAndoridApp = utilJs.isAndroidAudioApp() && this.hasPermission && !this.isFromColumn; //专栏听音频暂时也先走网页
    this.isMounted = true;
    playTimeControl = null;
    isDeactivated = false; //是否销毁对象，解决销毁了会继续出发audioTimeUpdate 导致audioTime无法为0
    isCanPlay = false; //是否能开始播放音频
    pageStatus = "visible";
    hiddenPlay = 0;
    this.isUseWxOpenAudio = this.getIsUseWxOpenAudio();
    if (this.isUseWxOpenAudio) {
      this.isRateMenuClickChange = false;
      clearInterval(playTimeControl);
      this.playStatus = 0;
      this.audioPlayTime = 0;
      this.duration = 0;
      // this.isNeedFirstPlay = false;
      this.isFirstPlay = true;
    }
    this.initAudio();
  },
  activated() {
    console.log("activated----");
    console.log(this.audioPlayTime, this.hasPermission);
    this.isUseWxOpenAudio = this.getIsUseWxOpenAudio();
    this.isRateMenuClickChange = false;
    this.initAudio();
    isDeactivated = false;
    // isPlaySuccess = 0;
    pageStatus = "visible";
    hiddenPlay = 0;
    this.aduioObj = null;
    this.hisPlayTime = 0;
    // dragStartTime = 0;
    clearInterval(playTimeControl);
    this.isClicked = false;
    this.ckFrom = this.$route.query.ckFrom;
    this.isIosApp = utilJs.isIosAudioApp();
    this.isAndoridApp = utilJs.isAndroidAudioApp();
    this.isHls = "";
  },
  deactivated() {
    isDeactivated = true;
    document.removeEventListener("visibilitychange", this.visibilitychange);
    clearInterval(playTimeControl);
    this.playStatus = 0;
    this.audioPlayTime = 0;
    this.duration = 0;
    this.playbackRate = 1;
    this.isNeedFirstPlay = false;
    this.isFirstPlay = true;
    console.log("deactivated----");
    console.log(this.audioPlayTime);
  }
};
</script>
<style scoped>
.audio-icon:active {
  color: #569ef8;
}
.process-style {
  background-color: #569ef8;
}
.process-style2 {
  background-color: #333;
}
.rail-style {
  background-color: rgba(242, 242, 242, 0.5);
}
.vue-slider {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.dot-style {
  width: 4px;
  height: 6px;
  background: #333;
  border-radius: 1px;
  margin-top: 5px;
}
.dot-inner {
  font-size: 10px;
  color: #fff;
  width: 68px;
  height: 14px;
  padding-left: 8px;
  padding-right: 8px;
  position: relative;
  border-radius: 16px;
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.2);
  background: #333!important;
}
.dot-inner span{
  text-align: center;
  position: absolute;
   top: 50%;
   left: 50%;
   width: 68px;
    transform: translate(-50%,-50%);
}
.audio-auditon {
  border: solid 2px #fff;
  top: -0.15rem;
  right: -1.1rem;
  background-color: #569ef8;
}
.c-p-t70 {
  top:1.75rem;
}
.c-p-t76 {
  top:1.9rem;
}
.rate-bg {
  background: url("../../../../assets/i/wap/course/rate_bg.png") no-repeat;
  background-size: 100% 100%;
}
.white-opacity {
  color: rgba(255, 255, 255, 0.4);
}
</style>
<style>
.audioPlay .vue-slider-dot {
  width: auto !important;
  height: 16px !important;
}
</style>
